﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ComponentModel;
using System.Windows.Forms;

namespace Lottery.MediaData.Core {
    /// <summary>
    /// 电子表格Helper
    /// </summary>
    public static class ETHelper {
        public static void Export(string qiShu, string cc, int maxCount, int ccIndex, FTCellData ft) {
            var path = cc == string.Empty ? DataHelper.ExcelPath_14 : DataHelper.GetExcelPath(maxCount);
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            string fileName;
            if (cc == string.Empty) fileName = path + "四表格过滤表_" + qiShu + "_14场.xlsx";
            else fileName = path + "四表格过滤表_" + qiShu + "_" + maxCount.ToString() + "场-" + ccIndex.ToString() + ".xlsx";

            if (System.IO.File.Exists(fileName)) {
                if (MessageBox.Show("当前过滤表已经被导出过，如果再次导出原有的过滤表Excel文件会被覆盖。\n\n请确认是否导出?",
                    "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2)
                    != DialogResult.Yes) {
                    return;
                }
            } else {
                if (MessageBox.Show("请确认是否导出过滤表?", "提示",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Information,
                        MessageBoxDefaultButton.Button2) != DialogResult.Yes) {
                    return;
                }
            }

            WaitForm form = new WaitForm();
            form.SetInfo("正在生成过滤表Excel文件，请稍等...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var dataInput = new List<string>();
                for (int row = 0; row < ft.RowCount; row++) {
                    for (int col = 0; col < ft.ColCount; col++) {
                        dataInput.Add(ft[col, row]);
                    }
                }

                Lottery.WPSOffice.ExcelGen.Run(fileName, qiShu, dataInput);
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private static FTCellData m_data;

        public static void Import(string fileName, out FTCellData data) {
            var d = Lottery.WPSOffice.ExcelGen.Import(fileName);
            m_data = new FTCellData();
            for (int row = 0; row < d.Count; row++) {
                m_data.AddRow(d[row]);
            }

            data = m_data;
        }

        /// <summary>
        /// 从Excel中批量导入媒体数据
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="qiShu"></param>
        /// <returns></returns>
        public static string Import2(string fileName, string qiShu) {
            var result = "成功导入数据";
            var form = new WaitForm();
            form.SetInfo("正在导入数据，请稍等...");

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var data = Lottery.WPSOffice.ExcelGen.Import2(fileName);
                for (int i = 0; i < data.Count; i++) {
                    foreach (var item in data[i]) {
                        if (string.IsNullOrEmpty(item)) {
                            result = string.Format("序号为 {0} 的数据不完整,不能导入", i + 1);
                            return;
                        }
                    }
                }

                foreach (var item in data) {
                    //表一
                    var subIndex = DataHelper.AutoIncSubIndex("T1", qiShu, string.Empty, 14);

                    var d = new List<DS>();
                    for (int i = 0; i < 14; i++) {
                        d.Add(new DS(int.Parse(item[i * 3]), int.Parse(item[i * 3 + 1]), int.Parse(item[i * 3 + 2]), string.Empty));
                    }
                    var t = DSHelper.ProcessAllData(d);
                    var f = new List<FD>();
                    foreach (var it in t) {
                        f.Add(new FD(it.Key, it.Value, 0, it.Value, true));
                    }
                    var cl = new CL() { From1 = -1, From2 = -1, To1 = -1, To2 = -1 };
                    DataHelper.SaveT1Data(qiShu, string.Empty, 14, subIndex, d, f, cl);

                    //表二
                    var subIndex2 = DataHelper.AutoIncSubIndex("T2", qiShu, string.Empty, 14);
                    var d2 = new List<SC>();
                    for (int i = 0; i < 14; i++) {
                        var sc = new SC() { Three = int.Parse(item[i * 3]), One = int.Parse(item[i * 3 + 1]), Zero = int.Parse(item[i * 3 + 2]), PreNumber = string.Empty };
                        sc.CalcDZX();
                        d2.Add(sc);
                    }
                    var t2 = SCHelper.ProcessAllData(d2);
                    var f2 = new List<FD>();
                    foreach (var it in t2) {
                        f2.Add(new FD(it.Key, it.Value, 0, it.Value, true));
                    }
                    var c2 = new CL() { From1 = -1, From2 = -1, To1 = -1, To2 = -1 };
                    DataHelper.SaveT2Data(qiShu, string.Empty, 14, subIndex2, d2, f2, c2);
                }
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();

            return result;
        }

        public static string Import3(string fileName, string qiShu, int maxCount) {
            var result = "成功导入数据";
            var form = new WaitForm();
            form.SetInfo("正在导入数据，请稍等...");

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var data = Lottery.WPSOffice.ExcelGen.Import3(fileName);
                for (int i = 0; i < data.Count; i++) {
                    var list = new List<string>();
                    for (int j = 0; j < maxCount; j++) {
                        var item = data[i][j];
                        if (string.IsNullOrEmpty(item)) {
                            result = string.Format("序号为 {0} 的数据不完整,不能导入", i + 1);
                            return;
                        }

                        list.Add(item);
                    }
                    var c = (from item in list select item).Distinct().Count();
                    if (c != maxCount) {
                        result = string.Format("序号为 {0} 的数据只有 {1} 场,应该有 {2} 场.数据不完整,不能导入", i, c, maxCount);
                        return;
                    }

                    var lt = (from item in list orderby int.Parse(item) select item).ToArray();
                    var cc = lt[0];
                    for (int idx = 1; idx < maxCount; idx++) {
                        cc += "-" + lt[idx];
                    }

                    DataHelper.SaveCC(qiShu, cc, maxCount);
                }
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();

            return result;
        }

        // 表3：从Excel中批量调入数据：调入预测文字
        public static string Import4(string fileName, string qiShu, int maxCount, List<int> ccList, string ccString) {
            var result = "成功导入数据";
            var form = new WaitForm();
            form.SetInfo("正在导入数据，请稍等...");

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var data = Lottery.WPSOffice.ExcelGen.Import4(fileName);
                // 检查数据正确
                var checkData = new List<string>() { "大", "中", "小" };
                for (int i = 0; i < data.Count; i++) {
                    for (int j = 0; j < 14; j++) {
                        var item = data[i][j];

                        if (string.IsNullOrEmpty(item) || checkData.IndexOf(item) == -1) {
                            result = string.Format("序号为 {0} 的数据不完整,不能导入", i + 1);
                            return;
                        }
                    }
                }
                var allSubIndex = DataHelper.GetT3SubIndexes(qiShu, ccString, maxCount);
                for (int i = 0; i < data.Count; i++) {
                    var subIndexTemp = from item in allSubIndex
                                       where item == (i + 1).ToString()
                                       select item;
                    var subIndexExists = subIndexTemp.Count() != 0;
                    var subIndex = "";
                    if (subIndexExists) {
                        subIndex = (i + 1).ToString();
                    } else {
                        subIndex = DataHelper.CreateSubIndex("T3", qiShu, ccString, maxCount, i + 1);
                    }

                    var d = new List<DZX>();
                    var dTemp = new List<DZX>();
                    CellData f;
                    if (subIndexExists) {
                        DataHelper.LoadT3Data(qiShu, ccString, maxCount, subIndex, out dTemp, out f);
                    }
                    for (int j = 0; j < 14; j++) {
                        if (ccList.IndexOf(j) == -1) {
                            d.Add(new DZX() {
                                D = "", Z = "", X = "",
                                Three = int.MinValue, One = int.MinValue, Zero = int.MinValue,
                                PreNumber = "", PreText = ""
                            });
                        } else {
                            if (!subIndexExists) {
                                d.Add(new DZX() {
                                    D = "", Z = "", X = "",
                                    Three = 0, One = 0, Zero = 0,
                                    PreNumber = "", PreText = data[i][j]
                                });
                            } else {
                                var item = dTemp[j];
                                item.PreText = data[i][j];
                                d.Add(item);
                            }
                        }
                    }

                    DataHelper.SaveT3Data(qiShu, ccString, maxCount, subIndex, d, DZXHelper.Gen(d));
                }
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();

            return result;
        }

        // 表4：从Excel中批量调入数据：调入预测文字
        public static string Import5(string fileName, string qiShu, int maxCount, List<int> ccList, string ccString) {
            var result = "成功导入数据";
            var form = new WaitForm();
            form.SetInfo("正在导入数据，请稍等...");

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var data = Lottery.WPSOffice.ExcelGen.Import5(fileName);
                // 检查数据正确
                var checkData = new List<string>() { "大", "中", "小", "首", "次", "末" };
                for (int i = 0; i < data.Count; i++) {
                    for (int j = 0; j < 14; j++) {
                        var item = data[i][j];

                        if (string.IsNullOrEmpty(item) || checkData.IndexOf(item) == -1) {
                            result = string.Format("序号为 {0} 的数据不完整,不能导入(有非法字符：{1})", i + 1, item);
                            return;
                        }
                    }
                }

                for (int i = 0; i < data.Count; i++) {
                    var textList = new List<string>() { "大", "中", "小" };
                    var text = "";
                    if (textList.IndexOf(data[0][0]) != -1) {
                        text = "大中小";
                    } else {
                        text = "首次末";
                    }

                    var subIndex = DataHelper.AutoIncSubIndex("T4", qiShu, ccString, maxCount);

                    var d = new List<WZ>();
                    for (int j = 0; j < 14; j++) {
                        if (ccList.IndexOf(j) == -1) {
                            d.Add(new WZ() { Three = "", One = "", Zero = "", PreText = "" });
                        } else {
                            if (text == "大中小")
                                d.Add(new WZ() { Three = "大", One = "中", Zero = "小", PreText = data[i][j] });
                            else
                                d.Add(new WZ() { Three = "首", One = "次", Zero = "末", PreText = data[i][j] });
                        }
                    }

                    DataHelper.SaveT4Data(qiShu, ccString, maxCount, subIndex, d, WZHelper.Gen(d), text);
                }
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();

            return result;
        }

        /// <summary>
        /// 过滤表导入限制表，表1用
        /// </summary>
        /// <returns></returns>
        public static string ImportLimitTable1(string fileName, FTCellData data) {
            var result = "成功导入数据";
            var form = new WaitForm();
            form.SetInfo("正在导入数据，请稍等...");

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var d = Lottery.WPSOffice.ExcelGen.ImportLimitTable1(fileName);

                // 最后7行
                for (int row = 1; row < 8; row++) {
                    var validCount = data.GetRowValidCount(data.RowCount - row);
                    if (validCount == 0) continue;

                    var limit = d[d.Count - row][validCount];
                    if (!string.IsNullOrEmpty(limit) && limit != "0-0")
                        data[15, data.RowCount - row] = limit;
                }

                // 除最后7行之外的行
                for (int row = 0; row < data.RowCount - 7; row++) {
                    var limitName = data[17, row];
                    var lts = limitName.Split(' ');

                    var idx = lts[0];

                    for (int i = 0; i < d.Count - 7; i++) {
                        if (d[i][0] == idx) {
                            var validCount = data.GetRowValidCount(row);
                            if (d[i].Count > validCount) {
                                var limit = d[i][validCount];
                                if (!string.IsNullOrEmpty(limit) && limit != "0-0") {
                                    data[15, row] = limit;
                                }
                            }
                            break;
                        }
                    }
                }
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();
            return result;
        }

        /// <summary>
        /// 过滤表导入限制表，表2用
        /// </summary>
        /// <returns></returns>
        public static string ImportLimitTable2(string fileName, FTCellData data) {
            // 算法与导入表1一样
            return ImportLimitTable1(fileName, data);
        }

        /// <summary>
        /// 过滤表导入限制表，表3用
        /// </summary>
        /// <returns></returns>
        public static string ImportLimitTable3(string fileName, FTCellData data) {
            var result = "成功导入数据";
            var form = new WaitForm();
            form.SetInfo("正在导入数据，请稍等...");

            var bw = new BackgroundWorker();
            bw.DoWork += (sender, e) => {
                var d = Lottery.WPSOffice.ExcelGen.ImportLimitTable3(fileName);
                for (int row = 0; row < 4; row++) {
                    var limit = d[row][0];
                    if (!string.IsNullOrEmpty(limit) && limit != "0-0") {
                        data[15, row] = limit;
                    }
                }

                for (int row = 4; row < 16; row++) {
                    var validCount = data.GetRowValidCount(row);
                    if (validCount == 0) continue;

                    if (d[row].Count > validCount) {
                        var limit = d[row][data.GetRowValidCount(row)];
                        if (!string.IsNullOrEmpty(limit) && limit != "0-0") {
                            data[15, row] = limit;
                        }
                    }
                }
            };
            bw.RunWorkerCompleted += (sender, e) => { form.Close(); };
            bw.RunWorkerAsync();
            form.ShowDialog();
            return result;
        }

        /// <summary>
        /// 过滤表导入限制表，表4用
        /// </summary>
        /// <returns></returns>
        public static string ImportLimitTable4(string fileName, FTCellData data) {
            // 与导入表3算法一致
            return ImportLimitTable3(fileName, data);
        }
    }
}
